package com.yang.demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yang.demo.constants.RedisPrefix;
import com.yang.demo.entity.Admin;
import com.yang.demo.entity.Menu;
import com.yang.demo.mapper.MenuMapper;
import com.yang.demo.service.IMenuService;
import com.yang.demo.utils.AdminUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author shi
 * @since 2021-04-16
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Resource
    private MenuMapper menuMapper;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 根据id获得菜单列表
     * @return
     */
    @Override
    public List<Menu> getMenuByAdminId() {
        //获取Security的全局上下文对象
        Integer adminId = AdminUtils.getCurrentAdmin().getId();
        //从redis中获取菜单数据
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        List<Menu> menus = (List) valueOperations.get("menu_" + adminId);
        //判断是否为空,如果为空,从数据库中获取
        if (CollectionUtils.isEmpty(menus)){
            menus = menuMapper.getMenuByAdminId(adminId);
            valueOperations.set(RedisPrefix.MENU_KEY+adminId,menus);
        }
        return menus;
    }

    /**
     * 查询所有菜单列表
     * @return
     */
    @Override
    public List<Menu> getAllMenus() {
        return menuMapper.getAllMenus();
    }

    /**
     * 根据角色获取菜单列表
     * @return
     */
    @Override
    public List<Menu> getMenusWithRole() {
        return menuMapper.getMenuWithRole();
    }
}
